package cn.com.callback

import cn.com.elite.EliteBean
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.Part
import java.text.SimpleDateFormat

public class apiSlowSQLToDB implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSlowSQLToDB.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {


        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        String savePath = "/data/apache-tomcat-dabc/temp";

        //确认文件夹存在
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }

        String fileName = null;
        try {
            log.debug("待上传文件请求List：" + request.getParts());
            Collection<Part> parts = request.getParts();

            //循环接收文件并保存
            int i = 0;
            int fileNum = parts.size();
            for (Part part : parts) {
                i++;
                String header = part.getHeader("content-disposition");
                log.debug("接收上传文件[" + i + "/" + fileNum + "]：" + header);
                if (header.indexOf("filename") != -1) {

                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    String timeStamp = df.format(new Date());

                    fileName = timeStamp + "-" + getFileName(header);
                    log.debug("获取文件名称[" + i + "/" + fileNum + "]：" + fileName);
					
                    part.write(savePath + File.separator + fileName);
                    log.debug("文件存储成功[" + i + "/" + fileNum + "]：" + fileName);

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }

        //return (savePath + "\\" + fileName);
        return "http://127.0.0.1:8090/tomcat.png";
    }

    public static String getFileName(String header) {// 这个方法通过header获取文件的名字
        String fileName = null;
        fileName = header.substring(header.indexOf("filename") + 2 + "filename".length(), header.length());
        fileName = fileName.substring(0, fileName.indexOf("\""));
        return fileName;
    }
}